from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from celery_tasks.detail.tasks import generate_detail_html
from goods.models import SKUImage
from meiduo_admin.serializers.images import ImageSerializers
from meiduo_admin.utils.pagination import MeiduoPagination
from rest_framework import serializers
from django.conf import settings


class ImagesView(ModelViewSet):
    queryset = SKUImage.objects.all().order_by('-id')
    serializer_class = ImageSerializers
    pagination_class = MeiduoPagination

    def create(self, request, *args, **kwargs):
        sku_id = request.data.get('sku')
        image_file = request.data.get('image')

        if not all([sku_id, image_file]):
            serializers.ValidationError('数据不完整')

        client = Fdfs_client(settings.FDFS_CLIENT_PATH)

        ret = client.upload_by_buffer(image_file.read())

        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传失败')
        image_name = ret['Remote file_id']

        image = SKUImage.objects.create(sku_id=sku_id, image=image_name)
        sku = image.sku
        if not image.sku.default_image:
            sku.default_image=image.image
            sku.save()
            generate_detail_html(sku.id)
        # 5.响应
        serializer = self.get_serializer(image)
        return Response(serializer.data, status=201)


    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        instance.delete()
        client =Fdfs_client(settings.FDFS_CLIENT_PATH)
        client.delete_file(instance.image.name)

        return Response(status=204)


    def update(self, request, *args, **kwargs):
        sku_id = request.data.get('sku')
        image_file = request.data.get('image')

        if not all([sku_id, image_file]):
            serializers.ValidationError('参数不全')

        instance = self.get_object()


        client = Fdfs_client(settings.FDFS_CLIENT_PATH)
        client.delete_file(instance.image.name)

        ret = client.upload_by_buffer(image_file.read())
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传失败')
        image_name = ret['Remote file_id']

        instance.sku_id=sku_id
        instance.image=image_name
        instance.save()

        serializer = self.get_serializer(instance)
        return Response(serializer.data, status=201)
